<template>
  <div class="father" style="font-family: Cera-Bold, sans-serif;">
    <el-container class="el-container">
      <el-aside width="200px"></el-aside>
      <el-main>
        <el-card>
          <el-row
            ><span
              >Please enter your activity title<span class="red-asterisk">
                *</span
              ></span
            ></el-row
          >
          <el-row class="content">
            <el-input v-model="form.title" placeholder="请输入内容"></el-input>
          </el-row>

          <el-row
            >
            <span>Tags<span class="red-asterisk"> *</span></span>
            </el-row>
          <el-row class="content">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入标签，按回车确认"
              class="custom-select"
            >
              <el-option
                v-for="item in existingTags"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-row>

          <el-row
          ><span>选择封面图片</span></el-row
          >
          <el-row class="content">
            <el-upload
                action="#"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :auto-upload="false"
                :on-change="handleUploadChange"
                :limit="1"
                :on-exceed="handleExceed">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" size="tiny">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-row>

          <el-row
            ><span
              >Please enter a description<span class="red-asterisk">
                *</span
              ></span
            ></el-row
          >
          <el-row class="content">
            <div ref="quillEditor" class="quill-editor"></div>
            <!-- Quill 编辑器 -->
          </el-row>
          <el-row class="word-count">{{ wordCount }}/{{ maxWordCount }}</el-row>

          <el-row><span></span></el-row>

          <el-row>
            <div
              style="
                height: 1px;
                width: 100%;
                margin-bottom: 10px;
                background-color: rgb(128, 128, 128);
              "
            ></div>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-button
                @click="resetForm"
                style="
                  width: 100%;
                  background-color: #1f2d3d;
                  color: white;
                  font-weight: bold;
                "
                >RESET
              </el-button>
            </el-col>
            <el-col :span="8" :offset="8">
              <el-button
                @click="submitForm"
                style="
                  width: 100%;
                  background-color: #ffbd00;
                  color: black;
                  font-weight: bold;
                "
                >SUBMIT
              </el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-main>

      <el-aside
        class="el-aside-right"
        width="200px"
        style="background-color: transparent"
      ></el-aside>
    </el-container>
  </div>
</template>

<script>
import Quill from "quill";
import "quill/dist/quill.snow.css";
import { postRequest } from "@/api/request";
import { postFormDataRequest } from "@/api/api";

export default {
  data() {
    return {
      wordCount: 0,
      maxWordCount: 2000,
      form: {
        title: "",
        details: "",
        fileList: [],
        tags: [],
        imageUrl: "",
      },
      dialogImageUrl: "",
      dialogVisible: false,
      existingTags: ["科研idea", "思考", "随便说"],
    };
  },
  methods: {
    // 保存表单数据到localStorage
    saveFormToLocalStorage() {
      try {
        // 创建表单数据的副本，排除文件对象（不能被序列化）
        const formDataCopy = { ...this.form };
        
        // 保存编辑器内容
        if (this.quill) {
          formDataCopy.details = this.quill.root.innerHTML;
        }
        
        localStorage.setItem('uploadActivity_formData', JSON.stringify(formDataCopy));
        console.log('活动表单数据已保存到localStorage');
      } catch (error) {
        console.error('保存活动表单数据失败:', error);
      }
    },
    
    // 从localStorage恢复表单数据
    restoreFormFromLocalStorage() {
      try {
        const savedData = localStorage.getItem('uploadActivity_formData');
        if (savedData) {
          const parsedData = JSON.parse(savedData);
          
          // 恢复基本表单字段
          Object.keys(parsedData).forEach(key => {
            this.form[key] = parsedData[key];
          });
          
          // 恢复编辑器内容
          if (parsedData.details && this.quill) {
            this.quill.root.innerHTML = parsedData.details;
            this.updateWordCount();
          }
          
          console.log('活动表单数据已从localStorage恢复');
        }
      } catch (error) {
        console.error('恢复活动表单数据失败:', error);
      }
    },
    
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      this.form.fileList = fileList;
      this.form.imageUrl = ''; // 清除已上传的图片URL
      this.saveFormToLocalStorage(); // 更新localStorage
    },
    handleSuccess(response, file, fileList) {
      this.form.fileList = fileList;
      this.saveFormToLocalStorage(); // 更新localStorage
    },
    async submitForm() {
      // 表单验证
      if (!this.form.title.trim()) {
        this.$message.error('请输入活动标题');
        return;
      }
      if (!this.form.tags || this.form.tags.length === 0) {
        this.$message.error('请至少选择一个标签');
        return;
      }
      const editorContent = this.quill.root.innerHTML.replace(/<[^>]*>/g, '').trim();
      if (!editorContent) {
        this.$message.error('请输入活动描述');
        return;
      }

      this.form.details = this.quill.root.innerHTML;
      console.log("Form submitted:", this.form);

      try {
        const response = await postRequest("/activities/createActivity", {
          title: this.form.title,
          description: this.form.details,
          imageUrl: this.form.imageUrl, // Add your image URL here
          videoUrl: "", // Add your video URL here
          startTime: new Date(), // Replace with actual start time
          endTime: new Date(), // Replace with actual end time
          tags: this.form.tags,
        });

        console.log("Server response:", response.data);
        this.$message({
          message: "上传成功",
          type: "success",
          duration: 700,
        });
        this.resetForm();
        // 提交成功后清除localStorage中的数据
        localStorage.removeItem('uploadActivity_formData');
        
      } catch (error) {
        console.error("Error submitting form:", error);
        this.$message.error("上传失败");
        // Handle the error
      }
    },
    resetForm() {
      this.form.title = "";
      this.form.fileList = [];
      this.form.tags = [];
      this.quill.root.innerHTML = "";
      this.clearEditor();
      
      // 重置表单后清除localStorage中的数据
      localStorage.removeItem('uploadActivity_formData');
    },
    initializeQuill() {
      const initialHeight = 200; // 初始高度
      this.$refs.quillEditor.style.height = `${initialHeight}px`; // 设置初始高度

      const editor = this.$refs.quillEditor;
      // 初始化 Quill 编辑器
      this.quill = new Quill(editor, {
        theme: "snow", // 使用 snow 主题
        placeholder: "   请输入描述...", // 默认显示的提示文字
        modules: {
          toolbar: [
            [{ header: "1" }, { header: "2" }, { font: [] }],
            [{ list: "ordered" }, { list: "bullet" }],
            ["bold", "italic", "underline"],
            [{ align: [] }],
            ["link"],
            ["image"],
          ],
        },
      });

      this.quill.on("text-change", () => {
        this.updateWordCount();
        this.adjustHeight(initialHeight);
        // 编辑器内容变化时保存表单数据
        this.saveFormToLocalStorage();
      });
      
      // 初始化后尝试恢复数据
      this.restoreFormFromLocalStorage();
    },
    adjustHeight(initialHeight) {
      // 获取编辑器的内容容器
      const editorContent = this.$refs.quillEditor.querySelector(".ql-editor");
      if (editorContent) {
        // 使用 Quill 的 getContents 方法获取 Delta 格式的内容
        const delta = this.quill.getContents();

        // 初始化内容高度，基于初始高度
        let contentHeight = initialHeight;

        // 遍历 Delta 内容
        delta.ops.forEach((op) => {
          if (typeof op.insert === "string") {
            // 按每行的高度累计（假设每行约 20px 高度）
            const lines = op.insert.split("\n").length - 1;
            contentHeight += lines * 20; // 可根据实际行高调整
          } else if (op.insert.image) {
            // 为每张图片追加固定高度（假设图片占 150px 高度）
            contentHeight += 350; // 可根据实际图片大小调整
          }
        });

        // 如果计算的内容高度大于初始高度，则调整编辑器高度
        if (contentHeight > initialHeight) {
          this.$refs.quillEditor.style.height = `${contentHeight}px`;
        }
      }
    },
    updateWordCount() {
      const text = this.quill.getText().trim(); // 获取 Quill 编辑器内容
      console.log("Text:", text);
      this.wordCount =
        text.length > this.maxWordCount ? this.maxWordCount : text.length; // 限制最大字数
    },
    clearEditor() {
      this.quill.setText(""); // 清空编辑器内容
      this.updateWordCount(); // 更新字数统计
    },
    handlePictureCardPreview(file) {
      console.log('url是', file.url)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    async handleUploadChange(file) {
      console.log('file是', file)
      try {
        // 创建 FormData 对象并添加文件
        const formData = new FormData()
        formData.append('file', file.raw)
        
        // 调用上传接口
        const url = await postFormDataRequest('/jobs/upload', formData)
        console.log('url是', url)
        
        // 处理上传成功
        this.handleUploadSuccess(url, file)
      } catch (error) {
        console.error('图片上传失败:', error)
        alert('图片上传失败')
      }
    },
    handleUploadSuccess(url, file) {
      // 这里处理上传成功后的逻辑
      this.form.imageUrl = url
      this.$emit('image-uploaded', url)
      
      // 图片上传成功后更新localStorage
      this.saveFormToLocalStorage();
    },
    handleExceed(files, fileList) {
      alert('只能上传一张图片')
    },
  },
  mounted() {
    // 在 mounted 生命周期钩子中初始化 Quill 编辑器
    this.initializeQuill();
    
    // 添加表单字段变化的监听
    this.$watch('form.title', () => this.saveFormToLocalStorage());
    this.$watch('form.tags', () => this.saveFormToLocalStorage());
  },
  // 添加beforeDestroy钩子，确保在组件销毁前保存数据
  beforeDestroy() {
    this.saveFormToLocalStorage();
  },
};
</script>

<style scoped>
.content {
  margin-bottom: 70px;
}

.red-asterisk {
  color: red;
}

.custom-select {
  width: 100%;
}

/* 覆盖 Element UI 的默认样式 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input) {
  width: 100%;
}

:deep(.el-select__tags) {
  width: 100%;
  flex-wrap: wrap;
}

/* 确保下拉菜单也足够宽 */
:deep(.el-select-dropdown) {
  width: auto !important;
  min-width: 100% !important;
}

.quill-editor {
  border: 1px solid #ddd;
  overflow: hidden; /* 防止内容超出容器 */
  transition: height 0.2s ease; /* 平滑调整高度 */
}

.word-count {
  text-align: right;
  margin-top: -70px;
  margin-bottom: 50px;
}
</style>